﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;

namespace Photography.Admin
{
    public class Email
    {
        private const string StartEmailPlaceholder = "<!--START_THE_EMAIL_BODY-->";
        private const string EndEmailPlaceholder = "<!--END_THE_EMAIL_BODY-->";
        private const string MessageTextPlaceHolder = "<!--MESSAGE_TEXT_PLACEHOLDER-->";
        private const string ImagePathPlaceHolder = "IMAGE_PATH_PLACEHOLDER";

        private const string ImageEmbeddingKey = "logoImage";
        private const string ImageEmbeddingKeyPrefix = "cid:";

        private string FullEmailTopHtml { get; set; }
        private string FullEmailBottomHtml { get; set; }

        public string BodyEmailTopHtml { get; private set; }
        public string BodyEmailBottomHtml { get; set; }

        private FileStream _logoImage;

        public Email(string templatePath, string logoFullImagePath, string logoRelativePath)
        {
            string template = File.ReadAllText(templatePath);
            string[] fullTopAndBottom = template.Split(new string[] { MessageTextPlaceHolder }, StringSplitOptions.None);
            string[] topHtml = fullTopAndBottom[0].Split(new string[] { StartEmailPlaceholder }, StringSplitOptions.None);
            string[] bottomHtml = fullTopAndBottom[1].Split(new string[] { EndEmailPlaceholder }, StringSplitOptions.None);

            FullEmailTopHtml = topHtml[0] + topHtml[1].Replace(ImagePathPlaceHolder, ImageEmbeddingKeyPrefix + ImageEmbeddingKey);
            FullEmailBottomHtml = bottomHtml[0] + bottomHtml[1];
            BodyEmailTopHtml = topHtml[1].Replace(ImagePathPlaceHolder, logoRelativePath);
            BodyEmailBottomHtml = bottomHtml[0];

            _logoImage = File.OpenRead(logoFullImagePath);
        }

        public void Send(MailAddressCollection to, string subject, string messageBody)
        {
            MailMessage message = new MailMessage();

            foreach (MailAddress email in to)
                message.To.Add(email);

            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = FullEmailTopHtml + messageBody + FullEmailBottomHtml;
            message.Bcc.Add("bishoyadel@gmail.com");

            AlternateView body = AlternateView.CreateAlternateViewFromString(FullEmailTopHtml + messageBody + FullEmailBottomHtml,
                null, MediaTypeNames.Text.Html);
            LinkedResource logo = new LinkedResource(_logoImage);
            logo.ContentId = ImageEmbeddingKey;
            body.LinkedResources.Add(logo);

            message.AlternateViews.Add(body);

            SmtpClient client = new SmtpClient();
            client.Send(message);
        }
    }
}